package edu.lingnan.blog.auth.mq;

import com.rabbitmq.client.Channel;
import edu.lingnan.blog.auth.form.LoginMessage;
import edu.lingnan.blog.common.core.constant.Constants;
import edu.lingnan.blog.common.core.constant.RabbitMQConstants;
import edu.lingnan.blog.common.core.domain.pojo.LoginInfo;
import edu.lingnan.blog.common.core.utils.ip.AddressUtils;
import edu.lingnan.blog.common.redis.service.RedisService;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author cql
 */
@Component
@RabbitListener(queues = {RabbitMQConstants.LOGIN_QUEUE})
public class LoginStatusReceiver {


    @Autowired
    private RedisService redisService;


    @Autowired
    public RedisTemplate redisTemplate;

    /**
     * 30天内登录2次及以上的省份会设定为常用登录地
     * 如果用户登录为非常用地，那么就会发送邮件提醒
     *
     * @param msg
     * @param loginMessage
     * @param channel
     */
    @RabbitHandler
    public void receiverMsg(Message msg, LoginMessage loginMessage, Channel channel) {
        // TODO 获取出UUID，然后存放进redis中，表示该消息已被消费
        String correlationId = msg.getMessageProperties().getCorrelationId();
        System.out.println(correlationId);

        long deliveryTag = msg.getMessageProperties().getDeliveryTag();
        try {
            LoginInfo loginInfo = new LoginInfo();
            BeanUtils.copyProperties(loginMessage, loginInfo);

            // 登录状态
            loginInfo.setStatus(loginMessage.isFlag() ? Constants.LOGIN_SUCCESS_STATUS : Constants.LOGIN_FAIL_STATUS);

            // 登录地点
            String address = AddressUtils.getRealAddressByIP(loginMessage.getIpaddr());
            loginInfo.setLoginLocation(address);


            // 获取用户登录浏览器等信息
            UserAgent userAgent = UserAgent.parseUserAgentString(loginMessage.getUserAgent());

            loginInfo.setBrowser(userAgent.getBrowser().getName());
            loginInfo.setOs(userAgent.getOperatingSystem().getName());

            // TODO 插入消息 / 异地登录提示

            System.out.println(loginInfo);
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            /**
             * 出现异常怎么办？如果没有basicAck的话，就会消息堆积
             */
            e.printStackTrace();
        }
    }


}
